const Subscription = require('egg').Subscription
const axios = require('axios');
const OneisallController = require('../controller/oneisall');
const moment = require('moment')
const cheerio = require('cheerio')

class SyncOne extends Subscription {
  // 通过 schedule 属性来设置定时任务的执行间隔等配置
  static get schedule() {
    return {
      cron: '0 0 6,8 * * *',
      type: 'worker',
      immediate: true
    };
  }

  // subscribe 是真正定时任务执行时被运行的函数
  async subscribe() {
    const { ctx } = this
    const { app } = ctx
    ctx.logger.warn('进入 one is all 定时任务');
    
    const ymd = moment().format('YYYY-MM-DD')

    const checkToday = await app.mysql.get(
        OneisallController.TABLE_ONE, { ymd }
    )

    if (checkToday) {
        ctx.logger.warn(`${ymd} 的 oneisall 已经存在，不重复抓取`)
        return {
          code: 500,
          msg: '今天已经同步过了',
          data: {
            ymd
          }
        }
    }

    const curlIndex = await axios.get('https://wufazhuce.com/')
    const $ = cheerio.load(curlIndex.data)
    const image = $('.fp-one-imagen').attr('src')
    const vol = $('.titulo').first().text().replaceAll('VOL.', '')
    const text = $('.fp-one-cita').first().find('a').text()

    const articleTitle = $('.one-articulo-titulo').first().find('a').clone().children().remove().end().text().trim()
    const articleAuthor = $('.one-articulo-titulo').find('a small').text().replaceAll('- ', '')
    const articleUrl = $('.one-articulo-titulo').find('a').attr('href')
    const curlArticle = await axios.get(articleUrl)
    const $article = cheerio.load(curlArticle.data)
    $article('.articulo-compartir').remove()
    const articleContent = $article('.one-articulo').first().html()
    const questionTitle = $('.one-cuestion-titulo').find('a').text().trim()
    const questionUrl = $('.one-cuestion-titulo').find('a').attr('href')
    const curlQuestion = await axios.get(questionUrl)
    const $question = cheerio.load(curlQuestion.data)
    const questionContent = $question('.cuestion-contenido').eq(1).html()


    const insertData = {
        ymd,
        image,
        text,
        vol,
        article_title: articleTitle,
        article_author: articleAuthor,
        article_content: articleContent,
        question_title: questionTitle,
        question_content: questionContent
    }
    
    const insertRes = await app.mysql.insert(OneisallController.TABLE_ONE, insertData)

    ctx.logger.warn(`${ymd} 的 oneisall 插入成功，插入结果：${insertRes}`)
    return {
      code: 200,
      msg: 'ok',
      data: {
        insertData,
        ymd,
        insertRes
      }
    }
  }
}

module.exports = SyncOne